//
//  AppDelegate.swift
//  SwiftWeiBo
//
//  Created by wyw on 16/9/15.
//  Copyright © 2016年 Style_Y. All rights reserved.
//

import UIKit

let SwitchRootViewControllerKey = "SwitchRootViewControllerKey"


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
        // 1.创建window   
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.backgroundColor = UIColor.white
        window?.rootViewController = defaultController()
        
        // 2.设置外观
        UINavigationBar.appearance().tintColor = UIColor.orange
        UITabBar.appearance().tintColor = UIColor.orange
        
        // 3.注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(AppDelegate.switchRoot(notify:)), name: NSNotification.Name(rawValue: SwitchRootViewControllerKey), object: nil)
        
        window?.makeKeyAndVisible()
        
        return true
    }
    
    // 切换控制器
    @objc private func switchRoot(notify:Notification) {
        
        if notify.object as! Bool
        {
            
            window?.rootViewController = MainViewController()
        } else {
            window?.rootViewController = WelcomeViewController()
        }
    }
    
    deinit {
        // 移除通知
        NotificationCenter.default.removeObserver(self)
    }
    
    // 跟界面
    private func defaultController() -> UIViewController {
      // 判断是否登录
        if UserAccount.userLogin() {
            return isNewUpdate() ? NewfeatureCollectionViewController() : WelcomeViewController()
        }
        
        // 没有登录
        return MainViewController()
    }
    
    private func isNewUpdate() -> Bool {
        // 1，获取版本号
        let newVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as! String
        
        // 2.获取以前的版本号 ?? "" 代表前边如果为nil，就设置为空字符串(因为字符串不能与nil比较)
        let oldVersion = UserDefaults.standard.object(forKey: "CFBundleShortVersionString") as? String ?? ""
        
        // 3.比较
        if newVersion.compare(oldVersion) == ComparisonResult.orderedDescending
        {
          // 新版本  存储当前版本号
            UserDefaults.standard.set(newVersion, forKey: "CFBundleShortVersionString")
            return true
        }
        
        return false
    }
}

